<?php


namespace App\EventListener;


use App\Utils\Helper\GetterHelper;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;

class ExceptionListener {
    protected $event;
    private $logger;

    public function __construct (LoggerInterface $logger) {
        $this->logger = $logger;
    }

    public function onKernelException (ExceptionEvent $event) {
        $this->event = $event;
        $this->main();
    }

    private function main () {
        // 发送钉钉报警日志
        // $this->dingTalkError();
    }

    /**
     * User: Gao
     * Date: 2020/4/19
     * Description: 发送钉钉报警日志
     */
    private function dingTalkError () {
        $client = HttpClient::create();
        $url = GetterHelper::getParameter('dingtalk_url');
        $website_domain = GetterHelper::getParameter('website_domain');
        $code = $this->event->getThrowable()->getCode();
        $request_uri = null;
        switch ($code) {
            case 0:
                if (method_exists($this->event->getThrowable(), 'getStatusCode')) {
                    $code = $this->event->getThrowable()->getStatusCode();
                } elseif (is_object($this->event->getThrowable()->getPrevious())) {
                    $code = $this->event->getThrowable()->getPrevious()->getCode();
                } else {
                    $code = 500;
                }
                break;
        }
        if (is_object($this->event->getRequest())) {
            $request_uri = $this->event->getRequest()->getRequestUri();
        }
        $content = '报警项目：'.$website_domain.PHP_EOL.PHP_EOL;
        if (!is_null($request_uri)) {
            $content .= '请求地址：'.$request_uri.PHP_EOL.PHP_EOL;
        }
        $client->request('POST', $url, [
            'json' => [
                'msgtype' => 'text',
                'text'    => [
                    'content' => $content.'错误类型：'.$code.PHP_EOL.PHP_EOL.'错误内容：'.$this->event->getThrowable()->getMessage().PHP_EOL.PHP_EOL.'报警时间：'.date('Y-m-d H:i:s').PHP_EOL.PHP_EOL,
                ],
                'at'      => [
                    'isAtAll' => true,
                ],
            ],
        ]);
    }
}